<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once(APPPATH.'controllers/Abstractfront.php');
class Login extends Abstractfront 
{

 	public function __construct() {
        parent::__construct();
       $this->load->model("usermodel");
    }

	public function index()
	{	

		if (isset($_COOKIE["token"])) {
           $username = $_COOKIE["username"];
           $result = $this->usermodel->getByUsername($username);
           if ($result["token"] == $_COOKIE["token"]) {
           		$data['password'] = $result['password'];
           		$data['username'] = $result['username'];
           } else {
           		$data['password'] = '';
           		$data['username'] = '';
           }
        } else {
        	$data['username'] = '';
        	$data['password'] = '';
        }
		$data['nav']='login';
		$this->load->view('login',$data);
	}

	public function checkLogin()
	{
	    $username = $this->input->post('username',true);
	    $password = $this->input->post('password',true);
	    $rememberMe = $this->input->post('remember',true);
	   
	    if(!$username)
	    {
	         self::json(array('code' => '0', 'msg' => '请输入用户名或密码!'));
	    }

	    if (!$password)
	    {
	         self::json(array('code' => '0', 'msg' => '密码输入错误！'));
	    }

	    $result = $this->usermodel->getByUsername($username);

	    if (!$result||$result['password'] !== $password)
	    {
	          self::json(array('code' => '0', 'msg' => '用户名或者密码错误，请重新输入 '));
	    }
	    if($result['type']==0){
              self::json(array('code' => '0', 'msg' => '权限错误！ '));
        }
       
       $_SESSION['user']=$result;
   		$guid=$this->guid();
   		$expire = time() + 86400*365;

       if ($rememberMe) {
       		$this->usermodel->updateToken($result['id'],$guid);
		    setcookie("token", $guid, $expire,"/");
		    setcookie("username", $result['username'], $expire, '/');
	    } else {
   			setcookie("token", '', time()-3000,"/");
   			setcookie("username", $result['username'], $expire, '/');
	    }

	    self::json(array('code' => '1', 'msg' => '登录成功，正在跳转中！'));
	}

	//退出登录
	public function signout() {
		$guid = $this->guid();
	    session_destroy();  
	    setcookie("token", $guid, time()-3000,"/");
	    header("location:/login/index");
	}

	function guid($prefix = ""){    //可以指定前缀
	    $str = md5(uniqid(mt_rand(), true));   
	    $uuid  = substr($str,0,8) . '-';   
	    $uuid .= substr($str,8,4) . '-';   
	    $uuid .= substr($str,12,4) . '-';   
	    $uuid .= substr($str,16,4) . '-';   
	    $uuid .= substr($str,20,12);   
	    return $prefix . $uuid;
	}
	
}
